package com.liuyucheng.idea_springboot.wechat.gzh.service.impl;

import com.liuyucheng.idea_springboot.constant.RedisKeyConstant;
import com.liuyucheng.idea_springboot.util.RedisUtil;
import com.liuyucheng.idea_springboot.wechat.gzh.entity.WechatToken;
import com.liuyucheng.idea_springboot.wechat.gzh.service.WechatGzhService;
import com.liuyucheng.util.EmptyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 微信公众号服务层
 * @author LiuYuCheng
 * @date 2023年11月20日 11:19
 */
@Slf4j
@Service
public class WechatGzhServiceImpl implements WechatGzhService {

    @Autowired
    private RedisUtil redisUtil;

    @Value("${wechat.gzh.appId}")
    private String appId;
    @Value("${wechat.gzh.appSecret}")
    private String appSecret;
    @Value("${wechat.host}")
    private String host;

    /**
     * 更新微信接口的access_token
     */
    @Override
    public String updateAccessToken() {
        String url = host+"/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={appSecret}";
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appId", appId);
        paramMap.put("appSecret", appSecret);
        ResponseEntity<WechatToken> entity = null;
        try {
            entity = new RestTemplate().getForEntity(url, WechatToken.class, paramMap);
        } catch (RestClientException e) {
            log.info("[更新access_token失败]");
            e.printStackTrace();
            return "";
        }
        WechatToken wechatToken = entity.getBody();
        if (!EmptyUtil.isEmpty(wechatToken.getErrcode())) {
            log.info("wechatToken：{}", wechatToken.getErrcode()+","+wechatToken.getErrmsg());
            Assert.isTrue("0".equals(wechatToken.getErrcode()), wechatToken.getErrmsg());
        }
        String accessToken = wechatToken.getAccess_token();
        redisUtil.setEx(RedisKeyConstant.WECHAT_GZH_ACCESS_TOKEN, accessToken, 7100, TimeUnit.SECONDS);
        return accessToken;
    }

    /**
     * 获取accessToken
     * @return
     */
    @Override
    public synchronized String getAccessToken(){
        Object accessToken = redisUtil.get(RedisKeyConstant.WECHAT_GZH_ACCESS_TOKEN);
        if(EmptyUtil.isEmpty(accessToken)){
            return updateAccessToken();
        }
        return accessToken.toString();
    }

    @Override
    public String updateMenu(String menuJson, String accessToken) {
        RestTemplate restTemplate = new RestTemplate();
        String url = host+"/cgi-bin/menu/create?access_token={access_token}";
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("access_token", accessToken);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("content-type", "text/html;charset=UTF-8");
        HttpEntity<Object> httpEntity = new HttpEntity<>(menuJson, httpHeaders);
        ResponseEntity<String> entity = restTemplate.postForEntity(url, httpEntity, String.class, paramMap);
        return entity.getBody();
    }
}
